
package com.welsy.authoring.business
{
	import mx.rpc.Fault;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.soap.mxml.WebService;	
	import mx.rpc.AbstractOperation;
	import com.adobe.cairngorm.business.ServiceLocator;
	import com.adobe.cairngorm.business.Responder;
	import mx.collections.ArrayCollection;
	import flash.utils.setTimeout;	
	import com.welsy.authoring.vo.CourseVO;
	import com.welsy.user.model.UserModelLocator;
		

	/**
	 * @version	$Revision: 1.1 $
	 */
	public class GetCoursesDelegate
	{
		public function GetCoursesDelegate( responder : Responder )
		{		
			this.service = ServiceLocator.getInstance().getWebService("CourseService") as WebService;
			this.responder = responder;
		}
		
		public function getCourses() : void
		{	
			getRealCourses();
			
			//demo
			//setTimeout(getFakeResult,1000,"");
		}
						
		private function getRealCourses() : void
		{			
			var o:AbstractOperation = service.getOperation("GetAllEditingCourses");
			o.arguments.GetAllCoursesRequest.AuthorID = UserModelLocator.getInstance().authorId;
			o.addEventListener(ResultEvent.RESULT, GetAllEditingCourses_onResult);
			o.addEventListener(FaultEvent.FAULT, GetAllEditingCourses_onFault);
			service.GetAllEditingCourses();			
			trace("GetAllEditingCourses");
		}	
		
		private function GetAllEditingCourses_onResult(event:ResultEvent):void
		{
			trace("GetAllEditingCourses_onResult");
			var coursesXMLList:XMLList = event.result as XMLList;
			var courses : ArrayCollection = new ArrayCollection();
			courses = parseXMLCourses(coursesXMLList)						
			responder.onResult(courses);
		}
		
		private function parseXMLCourses(list:XMLList):ArrayCollection
		{
			var courses : ArrayCollection = new ArrayCollection();
			var item:XML;
					
			list = list.descendants(CourseQNames.qnCourses).children();
			for each(item in list) {            	
            	var courseVO:CourseVO = new CourseVO;
				courseVO.setProperties(item);
				trace(courseVO.toString());
				courses.addItem(courseVO);            	            	
   			}
   			return courses;
		}
		
		private function GetAllEditingCourses_onFault(event:FaultEvent):void
		{
			trace("GetAllEditingCourses_onFault");	
			responder.onFault();		
		}
		
		private function getFakeResult(value:String): void
		{			
			var myAC : ArrayCollection = new ArrayCollection();
			var i:int;
			for (i = 0; i < 5; i++) {    
				var courseVO:CourseVO = new CourseVO;
				courseVO.id = i;
				courseVO.title = "corso"+i;
				myAC.addItemAt(courseVO, i);
			}
						
			if( 1 )
			{
				responder.onResult( myAC );
			}
			else
			{
				responder.onFault();
			}			
		}	
	
		private var responder : Responder;
		private var service : WebService;
	}

}